package com.yang.servlet;

import com.yang.pojo.Brand;
import com.yang.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/DeleteBrandMultiServlet")
public class DeleteBrandMultiServlet extends HttpServlet {
    //批量删除品牌
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("-----------------");
        BrandService brandService = new BrandService();
        List<Integer> fails = new ArrayList<>();
        String[] brandIds = request.getParameterValues("brandIds");
        for (int i = 0; i < brandIds.length; i++) {
            int brandId = Integer.parseInt(brandIds[i]);
            try {
                boolean b = brandService.deleteBrandById(brandId);
                if(b==false){
                    fails.add(brandId);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //提示信息
        String ids = "";
        for (Integer id : fails) {
            ids = ids + "," + id;
        }
        String tips = fails.size() == 0 ?"<label style='color:green'>多个品牌删除成功</label>":ids+"<label style='color:green'>多个品牌删除失败</label>";
        request.setAttribute("tips",tips);
        try {
            ArrayList<Brand> brands = brandService.findBrand();
            request.setAttribute("brands",brands);
            request.getRequestDispatcher("brand_manage.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
